<template lang="pug">
  #weather.weather(v-if='getShowWeather')
    .now.clearfix(@touchstart="showFutureWeather", ref="nowWrap")
      .weather-info.fl
        img(:src='getNowImage')
        p {{ getNowInfo }}
      .weather-temp.fl
        strong {{getCurWeather[0].high}}
        span ℃
    .future(@touchstart="hideFutureWeather", ref="futureWrap")
      .daily-top
        span {{ getWeatherResult.location.name }}
        i {{ getWeatherResult.last_update | fmtTime }}发布
      .daily-content
        .daily-today.clearfix
          .icon.fl
            img(:src='getNowImage', alt='')
          .temperature.fl
            strong {{ getCurWeather[0].high }}
            span ℃
            p {{ getNowInfo }}
          .quality.fr
            p 风向 {{ getCurWeather[0].wind_direction }}风
            p 风速 {{ getCurWeather[0].wind_speed }} km/小时
            p 风力等级 {{ getCurWeather[0].wind_scale }}级
        .daily-list.clearfix
          .daily-item.tac(v-for='(item, index) in weather')
            .date {{ item.date | fmtData }}
            .icon
              img(:src='item.dayimg', alt='')
            .text {{ item[getText()] }}
            .temperature
              | {{ item.low }}
              span ℃
              | /{{ item.high }}
              span ℃
</template>

<script>
import { getWeather } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      isShow: false,
      result: null,
      weather: null,
      weatherCookie: null,
      weatherNotFound: true
    }
  },
  mounted() {
    let that = this
    window['getData'] = function (data) {
      that.getWeatherData(data)
    }

    this.$nextTick(() => {
      const cookieName = 'weather' + this.panoInfo.pano_id
      this.weatherCookie = localStorage.getItem(cookieName)
      let temp
      if (this.weatherCookie && false) {
        try {
          temp = JSON.parse(this.weatherCookie)
        } catch (e) {
          // DO NOTHING
        }
        this.getWeatherData(temp)
      } else {
        getWeather(this.getPanoCity).request()
      }
      setTimeout(() => {
        // 说明没有请求到天气数据
        if (this.weatherNotFound) {
          let city = this.panoInfo.city
          if (city.indexOf('城区') != -1 || city.indexOf('郊县') != -1) {
            city = city.slice(0, -2)
          }
          getWeather(city).request()
        }
      }, 1000)
    })
  },
  computed: {
    ...mapGetters(['panoInfo']),
    getShowWeather() {
      return this.weatherCookie ? true : this.isShow ? true : false
    },
    getWeatherCookie() {
      if (this.weatherCookie) {
        return JSON.parse(this.weatherCookie)
      }
    },
    getWeatherResult() {
      if (this.result) {
        return this.result
      }
    },
    getCurWeather() {
      if (this.weather) {
        return this.weather
      }
    },
    getPanoCity() {
      if (this.panoInfo) {
        // 针对直辖市处理
        if (this.panoInfo.city.indexOf('城区') != -1 || this.panoInfo.city.indexOf('郊县') != -1) {
          return this.panoInfo.area.slice(0, -1)
        }
        return this.panoInfo.city
      }
    },
    getNowImage() {
      if (this.weather) {
        let name = this.weather[0][this.getCode()]
        return `${$globalconfig.URLS.API}krpano/images/weather/${name}.png`
      }
    },
    getNowInfo() {
      console.log(this.result)
      if (this.result) {
        return this.result.location.name + ' ' + this.weather[0][this.getText()]
      }
    }
  },
  methods: {
    showFutureWeather() {
      this.$refs.nowWrap.style.display = 'none'
      this.$refs.futureWrap.style.display = 'block'
    },
    hideFutureWeather() {
      this.$refs.nowWrap.style.display = 'block'
      this.$refs.futureWrap.style.display = 'none'
    },
    getCode() {
      return this.getDayOrNight('code')
    },
    getText() {
      return this.getDayOrNight('text')
    },
    getCodeList(index) {
      return this.weather[index][this.getCode()]
    },
    getDayOrNight(type) {
      var str
      var date = new Date()
      str = Number(date.getHours()) > 20 ? type + '_night' : type + '_day'
      return str
    },
    getWeatherData(json) {
      this.weatherNotFound = false
      if (json) {
        this.isShow = true
        this.result = json.results[0]
        this.weather = this.result.daily

        this.weather.map(item => {
          item.dayimg = `${$globalconfig.URLS.API}krpano/images/weather/${item.code_day}.png`
        })

        this._setNewCookie(json)
      }
    },
    _setNewCookie(json) {
      const name = json.results[0].location.name
      const cookeName = 'weather' + this.panoInfo.pano_id
      if (this.panoInfo.area.indexOf(name) == -1) {
        localStorage.removeItem(cookeName)
      }
      // 没有cookie则写入
      if (!this.weatherCookie) {
        localStorage.setItem(cookeName, JSON.stringify(json))
      }
    }
  },
  filters: {
    fmtTime(d) {
      // "2018-09-05T08:00:00+08:00"
      if (!d) return
      return d.split('+')[1]
    },
    fmtData(d) {
      let date = new Date()
      let res = '今天'
      let arr = d.split('-')
      if ((arr[arr.length - 1] - date.getDate()) == 1) {
        res = '明天'
      }
      if ((arr[arr.length - 1] - date.getDate()) == 2) {
        res = '后天'
      }
      return res
    }
  }
}
</script>

<style lang="stylus">
.weather
  width: 200px
  position: absolute
  top: 0
  font-size: 14px
  z-index: 9

  &:hover
    .future
      display: block

    .now
      display: none

  .now
    .weather-temp
      font-size: 0

      strong
        font-size: 40px
        margin-left: 6px
        color: #fff

      span
        font-size: 12px
        line-height: 45px
        vertical-align: top

    .weather-info
      p
        font-size: 14px

      img
        margin: 0
        width: 50px
        height: 50px

  .future
    width: 290px
    box-sizing: border-box
    border-radius: 4px
    // background: linear-gradient(#6f7c85,#919b9f)
    background: rgba(37, 37, 37, 0.72)
    margin-top: 10px
    display: none

    .daily-top
      padding: 10px 10px 0 10px

      span
        font-size: 14px

      i
        font-size: 12px

    .daily-content
      .daily-today
        padding-bottom: 10px

        .icon
          padding: 10px 0 0 14px
          width: 56px
          height: 56px

          img
            width: 100%
            height: 100%

        .temperature
          width: 80px
          margin-left: 10px
          margin-top: 20px

          strong
            font-size: 40px

          p
            font-size: 12px

        .quality
          width: 120px
          padding-right: 10px

          p
            padding-top: 6px

      .daily-list
        padding: 10px 0
        margin-top: 10px
        box-shadow: 0 -1px hsla(0, 0%, 100%, 0.2)

        .daily-item
          float: left
          width: 95px

          &:not(:last-child)
            border-right: 1px solid hsla(0, 0%, 100%, 0.2)

          .icon
            padding: 5px

            img
              width: 24px
              height: 24px
</style>
